package com.ybzl.common.core.controller;


import com.baomidou.mybatisplus.annotation.TableName;
import com.ybzl.common.utils.spring.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @description: 生成id工具类
 * @author: 233
 * @create: 2021-09-06 13:57
 **/
public class IdGenerator {

    private static final Logger logger = LoggerFactory.getLogger(IdGenerator.class);
    private static RedisTemplate redisTemplate = ApplicationContextHolder.getBeanByname("redisTemplate", RedisTemplate.class);

    /**
     * 获取年的后两位加上一年多少天+当前小时数作为前缀
     *
     * @param date
     * @return
     */
    private static String getOrderIdPrefix(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //补两位,因为一年最多三位数
        String monthFormat = String.format("%1$02d", month + 1);
        //补两位，因为日最多两位数
        String dayFormat = String.format("%1$02d", day);
        //补两位，因为小时最多两位数
        String hourFormat = String.format("%1$02d", hour);
        return year + monthFormat + dayFormat + hourFormat;
    }

    /**
     * 获取自增主键id
     *
     * @param object
     * @return
     */
    public static String getTableNameId(Object object) {
        String tableName = null;
        String tableNameId = null;
        TableName table = object.getClass().getAnnotation(TableName.class);
        if (table != null) {
            tableName = table.value();
            tableNameId = String.valueOf(orderId(tableName));
        }
        return tableNameId;
    }

    /**
     * 获取自增主键id
     *
     * @param object
     * @return
     */
    public static Long getTableNameIdLong(Object object) {
        String tableName = null;
        String tableNameId = null;
        TableName table = object.getClass().getAnnotation(TableName.class);
        if (table != null) {
            tableName = table.value();
            tableNameId = String.valueOf(orderId(tableName));
        }
        return Long.valueOf(tableNameId);
    }

    /**
     * 获取自增主键id
     *
     * @param object
     * @return
     */
    public static String getTableNameId(Object object, String sk) {
        String tableName = null;
        String tableNameId = null;
        TableName table = object.getClass().getAnnotation(TableName.class);
        if (table != null) {
            tableName = table.value();
            tableNameId = String.valueOf(orderId(tableName));
            if (!"".equalsIgnoreCase(sk) && sk != null) {
                tableNameId = sk + tableNameId;
            }
        }
        return tableNameId;
    }

    /**
     * 生成id
     *
     * @param tname 表名
     * @return
     */
    public static Long orderId(String tname) {
        String orderIdPrefix = getOrderIdPrefix(new Date());
        String key = "ID::" + tname + "_" + orderIdPrefix;
        String orderId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key, 1);
            redisTemplate.expire(key, 1, TimeUnit.HOURS);
            //往前补5位
            orderId = orderIdPrefix + String.format("%1$05d", increment);
        } catch (Exception e) {
            logger.error("生成ID号失败", e);
        }
        return Long.valueOf(orderId);
    }

    /**
     * 生成id
     *
     * @param tname 表名
     * @return
     */
    public static Long orderId(Class clazz) {
        return orderId(clazz.getName());
    }

    /**
     * @param tname  表名
     * @param prefix 前缀
     * @return
     */
    public static String orderId(String tname, String prefix) {
        String orderIdPrefix = getOrderIdPrefix(new Date());
        String key = "ID::" + tname + "_" + orderIdPrefix;
        String orderId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key, 1);
            redisTemplate.expire(key, 2, TimeUnit.HOURS);
            //往前补5位
            orderId = orderIdPrefix + String.format("%1$05d", increment);
        } catch (Exception e) {
            logger.error("生成ID号失败", e);
        }
        return prefix + orderId;
    }

    /**
     * 生成项目id
     *
     * @param prefix
     * @return
     */
    public static String projectId(String prefix) {
        String orderIdPrefix = getOrderIdPrefix(new Date());
        String key = "XM::" + prefix + "_" + orderIdPrefix;
        String orderId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key, 1);
            redisTemplate.expire(key, 1, TimeUnit.HOURS);
            //往前补5位
            orderId = orderIdPrefix + String.format("%1$05d", increment);
        } catch (Exception e) {
            System.out.println("生成ID号失败");
            e.printStackTrace();
        }
        return prefix + orderId;
    }
}
